import axios from 'axios'
import store from '@/store'
import { Message } from 'element-ui'

const service = axios.create({
  baseURL: 'https://api-hmzs.itheima.net/tj',
  timeout: 5000 // request timeout
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    const token = store.state.user.token
    if(token){
      config.headers.Authorization = token
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
      // Token 401处理
      const responsemsg = error.response?.status
      console.dir(responsemsg)


      if (responsemsg === 401) {
        // 1. 跳转到登录
        router.push('/login')
        // 2. 清空用户数据
        store.commit('user/clearUserInfo')
      }
        // 错误统一处理
        // Message.error(error.response.data.msg)
    return Promise.reject(error)
  }
)

export default service
